package com.bluefox.modules.security.security;

import com.bluefox.utils.SpringContextHolder;

import com.bluefox.modules.security.config.bean.SecurityProperties;
import com.bluefox.modules.security.security.vo.OnlineUser;
import com.bluefox.modules.security.service.OnlineUserService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @CLassName TokenFilter
 * @Description TODO 添加token过滤器  超类 GenericFilterBean
 * @Author 孙峰
 * @Date 2020/1/1 17:19
 * @Version 1.0
 */
@Slf4j
public class TokenFilter extends GenericFilterBean {
    private final TokenProvider tokenProvider;

    TokenFilter(TokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        // 从请求中获取token信息
        String token = resolveToken(httpServletRequest);
        String requestRri = httpServletRequest.getRequestURI();
        // 验证 token 是否存在
        OnlineUser onlineUser = null;
        try {
            // 获取配置信息
            SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
            OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
           // 获取在线用户信息
            onlineUser = onlineUserService.getOne(properties.getOnlineKey() + token);
        } catch (ExpiredJwtException e) {
            log.error(e.getMessage());
        }
        if (onlineUser != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
            Authentication authentication = tokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
        } else {
            log.debug("no valid JWT token found, uri: {}", requestRri);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 根据HttpServletRequest 获取token信息
     * @param request
     * @return String
     */
    private String resolveToken(HttpServletRequest request) {
        // 获取权限的配置类
        SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
        //从请求中获取到token信息
        String bearerToken = request.getHeader(properties.getHeader());
        //验证并处理token信息返回
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
